﻿namespace AllServer.Core.Util;

[UnifyModel(typeof(MyResult<>))]
public class SpeciallyResultProvider : IUnifyResultProvider
{
    /// <summary>
    /// 异常返回值
    /// </summary>
    /// <param name="context"></param>
    /// <param name="metadata"></param>
    /// <returns></returns>\
    public IActionResult OnException(ExceptionContext context, ExceptionMetadata metadata)
    {
        //异常信息捕捉收集
        //ExceptionlessClient.Default.SubmitException(context.Exception);

        return new JsonResult(ApiResponse(metadata.StatusCode, data: metadata.Data, errors: metadata.Errors)
            , UnifyContext.GetSerializerSettings(context));
    }

    /// <summary>
    /// 成功返回值
    /// </summary>
    /// <param name="context"></param>
    /// <param name="data"></param>
    /// <returns></returns>
    public IActionResult OnSucceeded(ActionExecutedContext context, object data)
    {
        return new JsonResult(ApiResponse(StatusCodes.Status200OK, true, data)
            , UnifyContext.GetSerializerSettings(context));
    }

    /// <summary>
    /// 验证失败/业务异常返回值
    /// </summary>
    /// <param name="context"></param>
    /// <param name="metadata"></param>
    /// <returns></returns>
    public IActionResult OnValidateFailed(ActionExecutingContext context, ValidationMetadata metadata)
    {
        return new JsonResult(ApiResponse(metadata.StatusCode ?? StatusCodes.Status400BadRequest, data: metadata.Data, errors: metadata.FirstErrorMessage)
            , UnifyContext.GetSerializerSettings(context)); // 当前行仅限 Furion 4.6.6+ 使用
    }

    /// <summary>
    /// 特定状态码返回值
    /// </summary>
    /// <param name="context"></param>
    /// <param name="statusCode"></param>
    /// <param name="unifyResultSettings"></param>
    /// <returns></returns>
    public async Task OnResponseStatusCodes(HttpContext context, int statusCode, UnifyResultSettingsOptions unifyResultSettings)
    {
        // 设置响应状态码
        UnifyContext.SetResponseStatusCodes(context, statusCode, unifyResultSettings);

        switch (statusCode)
        {
            // 处理 401 状态码
            case StatusCodes.Status401Unauthorized:
                await context.Response.WriteAsJsonAsync(ApiResponse(statusCode, errors: "401 Unauthorized")
                    , App.GetOptions<JsonOptions>()?.JsonSerializerOptions);
                break;
            // 处理 403 状态码
            case StatusCodes.Status403Forbidden:
                await context.Response.WriteAsJsonAsync(ApiResponse(statusCode, errors: "403 Forbidden")
                    , App.GetOptions<JsonOptions>()?.JsonSerializerOptions);
                break;
            default: break;
        }
    }

    /// <summary>
    /// 返回 RESTful 风格结果集
    /// </summary>
    /// <param name="statusCode"></param>
    /// <param name="succeeded"></param>
    /// <param name="data"></param>
    /// <param name="errors"></param>
    /// <returns></returns>
    private static MyResult<object> ApiResponse(int statusCode, bool succeeded = default, object data = default, object errors = default)
    {
        return new MyResult<object>
        {
            Code = statusCode,
            Data = data,
            Message = errors?.ToString() ?? "",
            Extras = UnifyContext.Take(),
            RequestId = App.HttpContext.Request.Headers["RequestId"].FirstOrDefault() ?? Guid.NewGuid().ToString("N")
        };
    }

    public IActionResult OnAuthorizeException(DefaultHttpContext context, ExceptionMetadata metadata)
    {
        throw new NotImplementedException();
    }
}

public class MyResult<T>
{
    /// <summary>
    /// 状态码
    /// </summary>
    public int Code { get; set; }

    /// <summary>
    /// 提示内容
    /// </summary>
    public string Message { get; set; }

    /// <summary>
    /// 返回数据
    /// </summary>
    public T Data { get; set; } = default;

    /// <summary>
    /// 请求的ID
    /// </summary>
    public string RequestId { get; set; }

    /// <summary>
    /// 附加数据
    /// </summary>
    public object Extras { get; set; } = default;
}
